<template>
  <div>
    <el-divider content-position="left">价格选择（价格更新时间:{{ lastUpdateTime }}）</el-divider>
    <el-row v-loading="loading" :gutter="20">
      <el-col :span="8">
        <el-form-item label="产品类型" prop="firstLevel">
          <el-select
            v-model="selectedFirstLevel"
            placeholder="请选择产品类型"
            style="width: 100%"
            @change="handleFirstLevelChange"
          >
            <el-option
              v-for="option in firstLevelOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="规格" prop="secondLevel">
          <el-select
            v-model="selectedSecondLevel"
            placeholder="请选择规格"
            style="width: 100%"
            :disabled="!selectedFirstLevel"
            @change="handleSecondLevelChange"
          >
            <el-option
              v-for="option in secondLevelOptions"
              :key="option"
              :label="option"
              :value="option"
            />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
      </el-col>
      <!-- 其他规格输入 -->
      <el-row v-if="selectedSecondLevel === '其他'">
        <el-col :span="8">
          <el-form-item label="宽度(mm)" prop="w">
            <el-input-number v-model="formData.w" :min="0" placeholder="宽度" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="长度(mm)" prop="l">
            <el-input-number v-model="formData.l" :min="0" placeholder="长度" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="全展(mm)" prop="h">
            <el-input-number
              v-model="formData.h"
              :min="0"
              placeholder="全展(mm)"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="12">
        <el-form-item label="工艺" prop="thirdLevel">
          <el-select
            v-model="selectedThirdLevel"
            placeholder="请选择工艺"
            style="width: 100%"
            :disabled="!selectedSecondLevel"
            @change="handleThirdLevelChange"
          >
            <el-option
              v-for="option in thirdLevelOptions"
              :key="option"
              :label="option"
              :value="option"
            />
            <el-option label="亮光镀铝" value="亮光镀铝" />
            <el-option label="亮光开窗" value="亮光开窗" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
      </el-col>
      <!-- 其他工艺输入 -->
      <el-col v-if="selectedThirdLevel === '其他'" :span="12">
        <el-form-item label="工艺名称" prop="bagProcess">
          <el-input
            v-model="formData.bagProcess"
            placeholder="请输入工艺名称"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="款数" prop="typeNum" label-width="100px">
          <el-input v-model="formData.typeNum" type="textarea" placeholder="" style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="20">
        <el-form-item label="设计图" prop="attach" label-width="100px">
          <FileUpload v-model="formData.attach" style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="其他规格" prop="remark2">
          <el-input
            v-model="formData.remark2"
            style="width: 100%"
            maxlength="2000"
            show-word-limit
            rows="4"
            type="textarea"
            placeholder="添加其他规格信息或者任意备注"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="selectedSecondLevel !== '其他' && selectedThirdLevel !== '其他'" :span="12">
        <el-form-item label="数量档次" prop="fourthLevel">
          <el-select
            v-model="selectedFourthLevel"
            placeholder="请选择数量档次(最多3个)"
            style="width: 100%"
            :disabled="!selectedThirdLevel"
            multiple
            :max-limit="3"
            @change="handleFourthLevelChange"
          >
            <el-option
              v-for="option in fourthLevelOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-divider content-position="left">数量信息</el-divider>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item :label="`数量1(${quantityUnit})`" prop="quantity1">
          <el-input-number
            v-model="formData.quantity1"
            :min="0"
            :placeholder="`数量1`"
            style="width: 100%"
            :disabled="selectedSecondLevel !== '其他' && selectedThirdLevel !== '其他'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="`数量2(${quantityUnit})`" prop="quantity2">
          <el-input-number
            v-model="formData.quantity2"
            :min="0"
            :placeholder="`数量2`"
            style="width: 100%"
            :disabled="selectedSecondLevel !== '其他' && selectedThirdLevel !== '其他'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="`数量3(${quantityUnit})`" prop="quantity3">
          <el-input-number
            v-model="formData.quantity3"
            :min="0"
            :placeholder="`数量3`"
            style="width: 100%"
            :disabled="selectedSecondLevel !== '其他' && selectedThirdLevel !== '其他'"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <template v-if="selectedSecondLevel !== '其他' && selectedThirdLevel !== '其他'">
      <el-divider content-position="left">价格信息</el-divider>
      <!-- 现货数码印印显示基本信息 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label-width="0px" prop="digital_info1">
            <DigitalPrintDisplay
              :form-data="enhancedFormData"
              :quantity="formData.quantity1"
              :submit-price="formData.price1"
              :final-price="formData.finalPrice1"
              :quote-number="1"
              :member-unit-price="memberUnitPrice1"
              :retail-unit-price="retailUnitPrice1"
              :member-total-price="memberTotalPrice1"
              :retail-total-price="retailTotalPrice1"
              :quantity-unit="quantityUnit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="0px" prop="digital_info2">
            <DigitalPrintDisplay
              :form-data="enhancedFormData"
              :quantity="formData.quantity2"
              :submit-price="formData.price2"
              :final-price="formData.finalPrice2"
              :quote-number="2"
              :member-unit-price="memberUnitPrice2"
              :retail-unit-price="retailUnitPrice2"
              :member-total-price="memberTotalPrice2"
              :retail-total-price="retailTotalPrice2"
              :quantity-unit="quantityUnit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="0px" prop="digital_info3">
            <DigitalPrintDisplay
              :form-data="enhancedFormData"
              :quantity="formData.quantity3"
              :submit-price="formData.price3"
              :final-price="formData.finalPrice3"
              :quote-number="3"
              :member-unit-price="memberUnitPrice3"
              :retail-unit-price="retailUnitPrice3"
              :member-total-price="memberTotalPrice3"
              :retail-total-price="retailTotalPrice3"
              :quantity-unit="quantityUnit"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </template>

    <!-- 订单信息：新增模式不显示重量和总价 -->
    <el-divider v-if="!isAddMode" content-position="left">订单信息</el-divider>
    <!-- 报价员模式在status=0,1时可以修改重量 -->
    <el-row
      v-if="
        !isAddMode &&
        isQuoteMode &&
        (formData.status === 0 || formData.status === 1 || formData.status === 3)
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="重量(kg)" prop="weight1">
          <el-input-number
            v-model="formData.weight1"
            :min="0"
            placeholder="重量"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量2" prop="weight2">
          <el-input-number
            v-model="formData.weight2"
            :min="0"
            placeholder="重量2"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量3" prop="weight3">
          <el-input-number
            v-model="formData.weight3"
            :min="0"
            placeholder="重量3"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 其他模式显示重量但不可编辑 -->
    <el-row
      v-if="
        !isAddMode &&
        (!isQuoteMode || (formData.status !== 0 && formData.status !== 1 && formData.status !== 3))
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="重量(kg)" prop="weight1">
          <el-input-number
            v-model="formData.weight1"
            :min="0"
            placeholder="重量"
            style="width: 100%"
            disabled
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量2" prop="weight2">
          <el-input-number
            v-model="formData.weight2"
            :min="0"
            placeholder="重量2"
            style="width: 100%"
            disabled
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="重量3" prop="weight3">
          <el-input-number
            v-model="formData.weight3"
            :min="0"
            placeholder="重量3"
            style="width: 100%"
            disabled
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 报价员模式在status=0,1时可以修改总价 -->
    <el-row
      v-if="
        !isAddMode &&
        isQuoteMode &&
        (formData.status === 0 || formData.status === 1 || formData.status === 3)
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="总价(元)" prop="price1">
          <el-input-number
            v-model="formData.price1"
            :min="0"
            placeholder="总价"
            style="width: 100%"
          />
          <div v-if="unitPrice1 > 0" class="unit-price-display">
            单价：{{ unitPrice1.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价2" prop="price2">
          <el-input-number
            v-model="formData.price2"
            :min="0"
            placeholder="总价2"
            style="width: 100%"
          />
          <div v-if="unitPrice2 > 0" class="unit-price-display">
            单价：{{ unitPrice2.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价3" prop="price3">
          <el-input-number
            v-model="formData.price3"
            :min="0"
            placeholder="总价3"
            style="width: 100%"
          />
          <div v-if="unitPrice3 > 0" class="unit-price-display">
            单价：{{ unitPrice3.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 其他模式显示总价但不可编辑 -->
    <el-row
      v-if="
        !isAddMode &&
        (!isQuoteMode || (formData.status !== 0 && formData.status !== 1 && formData.status !== 3))
      "
      :gutter="20"
    >
      <el-col :span="8">
        <el-form-item label="总价(元)" prop="price1">
          <el-input-number
            v-model="formData.price1"
            :min="0"
            placeholder="总价"
            style="width: 100%"
            disabled
          />
          <div v-if="unitPrice1 > 0" class="unit-price-display">
            单价：{{ unitPrice1.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价2" prop="price2">
          <el-input-number
            v-model="formData.price2"
            :min="0"
            placeholder="总价2"
            style="width: 100%"
            disabled
          />
          <div v-if="unitPrice2 > 0" class="unit-price-display">
            单价：{{ unitPrice2.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总价3" prop="price3">
          <el-input-number
            v-model="formData.price3"
            :min="0"
            placeholder="总价3"
            style="width: 100%"
            disabled
          />
          <div v-if="unitPrice3 > 0" class="unit-price-display">
            单价：{{ unitPrice3.toFixed(4) }} 元/个
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } from "vue";
import SysTextAPI from "@/api/system/sys-text.api";

defineOptions({
  name: "DigitalPrint",
  inheritAttrs: false,
});

const props = defineProps({
  formData: {
    type: Object,
    required: true,
  },
  isAddMode: {
    type: Boolean,
    default: false,
  },
  isQuoteMode: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:formData"]);

// 价格数据相关
const priceData = ref({});
const loading = ref(false);
const lastUpdateTime = ref("");
const firstLevelOptions = ref([]);
const secondLevelOptions = ref([]);
const thirdLevelOptions = ref([]);
const fourthLevelOptions = ref([]);
const selectedFirstLevel = ref("");
const selectedSecondLevel = ref("");
const selectedThirdLevel = ref("");
const selectedFourthLevel = ref([]);

// 判断是否为卷膜产品
const isRollFilm = computed(() => {
  return selectedFirstLevel.value === "卷膜" || props.formData.bagType === "卷膜";
});

// 获取数量单位
const quantityUnit = computed(() => {
  return isRollFilm.value ? "米" : "个";
});

// 缓存相关常量
const CACHE_KEYS = {
  PRICE_DATA: "digital_price_data",
  LAST_UPDATE_TIME: "digital_price_update_time",
};

// 从localStorage加载缓存数据
const loadCacheData = () => {
  try {
    const cachedPriceData = localStorage.getItem(CACHE_KEYS.PRICE_DATA);
    const cachedUpdateTime = localStorage.getItem(CACHE_KEYS.LAST_UPDATE_TIME);

    if (cachedPriceData && cachedUpdateTime) {
      priceData.value = JSON.parse(cachedPriceData);
      lastUpdateTime.value = cachedUpdateTime;
      firstLevelOptions.value = Object.keys(priceData.value);
      return true;
    }
    return false;
  } catch (error) {
    console.error("加载缓存数据失败:", error);
    return false;
  }
};

// 保存数据到localStorage
const saveCacheData = (data, updateTime) => {
  try {
    localStorage.setItem(CACHE_KEYS.PRICE_DATA, JSON.stringify(data));
    localStorage.setItem(CACHE_KEYS.LAST_UPDATE_TIME, updateTime);
  } catch (error) {
    console.error("保存缓存数据失败:", error);
  }
};

// 获取价格数据
const fetchPriceData = async () => {
  try {
    loading.value = true;

    // 先从缓存加载
    const hasCachedData = loadCacheData();

    // 检查服务器更新时间
    const serverUpdateTime = await SysTextAPI.getTextByKey("price_update");

    // 如果缓存数据存在且更新时间一致，直接使用缓存
    if (hasCachedData && serverUpdateTime === lastUpdateTime.value) {
      console.log("DigitalPrint: 使用缓存数据，更新时间一致");
      return;
    }

    // 需要重新获取数据
    console.log("DigitalPrint: 获取最新价格数据");
    const response = await SysTextAPI.getTextByKey("price");
    if (response) {
      priceData.value = JSON.parse(response);
      firstLevelOptions.value = Object.keys(priceData.value);
      lastUpdateTime.value = serverUpdateTime || new Date().toLocaleString();

      // 保存到缓存
      saveCacheData(priceData.value, lastUpdateTime.value);
    }
  } catch (error) {
    console.error("获取价格数据失败:", error);

    // 如果服务器获取失败，尝试使用缓存数据
    const hasCachedData = loadCacheData();
    if (hasCachedData) {
      console.warn("DigitalPrint: 服务器获取失败，使用缓存数据");
    }
  } finally {
    loading.value = false;
  }
};

// 处理第一级选择
const handleFirstLevelChange = (value) => {
  selectedFirstLevel.value = value;
  selectedSecondLevel.value = "";
  selectedThirdLevel.value = "";
  selectedFourthLevel.value = [];
  secondLevelOptions.value = [];
  thirdLevelOptions.value = [];
  fourthLevelOptions.value = [];

  // 更新 bagType 字段
  props.formData.bagType = value;

  // 清空规格相关字段，因为不同产品类型的规格格式不同
  props.formData.l = 0;
  props.formData.w = 0;
  props.formData.h = 0;

  if (value && priceData.value[value]) {
    secondLevelOptions.value = Object.keys(priceData.value[value]);
  }

  // 触发 formData 更新
  emit("update:formData", { ...props.formData });
};

// 处理第二级选择
const handleSecondLevelChange = (value) => {
  selectedSecondLevel.value = value;
  selectedThirdLevel.value = "";
  selectedFourthLevel.value = [];
  thirdLevelOptions.value = [];
  fourthLevelOptions.value = [];

  // 解析规格字符串并更新 l, w, h 字段
  // 先清空所有规格字段
  props.formData.l = 0;
  props.formData.w = 0;
  props.formData.h = 0;

  if (value && value !== "其他") {
    // 判断是否为卷膜产品
    if (selectedFirstLevel.value === "卷膜") {
      // 卷膜规格格式：'820mm'
      const rollMatch = value.match(/^(\d+)mm$/);
      if (rollMatch) {
        props.formData.l = parseInt(rollMatch[1]);
        // w 和 h 保持为 0
      }
    } else {
      // 普通规格格式：'100*150+35'
      const sizeMatch = value.match(/^(\d+)\*(\d+)\+(\d+)$/);
      if (sizeMatch) {
        props.formData.l = parseInt(sizeMatch[1]);
        props.formData.w = parseInt(sizeMatch[2]);
        props.formData.h = parseInt(sizeMatch[3]);
      }
    }

    if (
      value &&
      priceData.value[selectedFirstLevel.value] &&
      priceData.value[selectedFirstLevel.value][value]
    ) {
      thirdLevelOptions.value = Object.keys(priceData.value[selectedFirstLevel.value][value]);
    }
  } else if (value === "其他") {
    // 其他选项，清空工艺选项
    thirdLevelOptions.value = [];
  }

  // 触发 formData 更新
  emit("update:formData", { ...props.formData });
};

// 处理第三级选择
const handleThirdLevelChange = (value) => {
  selectedThirdLevel.value = value;
  selectedFourthLevel.value = [];
  fourthLevelOptions.value = [];

  // 更新 bagProcess 字段
  if (value !== "其他") {
    props.formData.bagProcess = value;
  }

  if (
    value &&
    value !== "其他" &&
    priceData.value[selectedFirstLevel.value] &&
    priceData.value[selectedFirstLevel.value][selectedSecondLevel.value] &&
    priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][value]
  ) {
    const originalKeys = Object.keys(
      priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][value]
    );

    // 生成选项，去掉"个"字，只保留数值
    const options = originalKeys.map((key) => {
      let numericValue = key.replace(/个$/, "");
      numericValue = numericValue.replace(/米$/, "");
      return {
        label: key,
        value: numericValue,
      };
    });
    options.sort((a, b) => a.value - b.value);
    fourthLevelOptions.value = options;
  } else if (value === "其他") {
    // 其他选项，清空数量档次选项
    fourthLevelOptions.value = [];
  }

  // 触发 formData 更新
  emit("update:formData", { ...props.formData });
};

// 处理第四级选择
const handleFourthLevelChange = (values) => {
  // 限制最多选择3个
  if (values.length > 3) {
    values = values.slice(0, 3);
  }

  selectedFourthLevel.value = values;

  // 更新数量信息到formData
  const quantities = [0, 0, 0];

  values.forEach((value, index) => {
    if (index < 3) {
      quantities[index] = parseInt(value) || 0;
    }
  });

  // 更新formData中的数量
  props.formData.quantity1 = quantities[0];
  props.formData.quantity2 = quantities[1];
  props.formData.quantity3 = quantities[2];

  // 触发 formData 更新
  emit("update:formData", { ...props.formData });
};

// 初始化选择状态（处理返回值）
const initializeSelections = () => {
  // 恢复产品类型选择
  if (props.formData.bagType) {
    selectedFirstLevel.value = props.formData.bagType;
    if (priceData.value[props.formData.bagType]) {
      secondLevelOptions.value = Object.keys(priceData.value[props.formData.bagType]);
    }
  }

  // 恢复规格选择（根据 l, w, h 重构规格字符串）
  if (props.formData.l) {
    let sizeString = "";

    // 判断是否为卷膜产品
    if (props.formData.bagType === "卷膜") {
      // 卷膜规格格式：'820mm'
      sizeString = `${props.formData.l}mm`;
    } else if (props.formData.w && props.formData.h) {
      // 普通规格格式：'100*150+35'
      sizeString = `${props.formData.l}*${props.formData.w}+${props.formData.h}`;
    }

    if (sizeString) {
      // 检查是否存在对应的规格选项
      const existingOptions = secondLevelOptions.value;
      if (existingOptions.includes(sizeString)) {
        selectedSecondLevel.value = sizeString;
      } else {
        // 如果不存在，设置为"其他"
        selectedSecondLevel.value = "其他";
      }

      if (
        selectedFirstLevel.value &&
        priceData.value[selectedFirstLevel.value] &&
        priceData.value[selectedFirstLevel.value][sizeString]
      ) {
        thirdLevelOptions.value = Object.keys(
          priceData.value[selectedFirstLevel.value][sizeString]
        );
      }
    }
  }

  // 恢复工艺选择
  if (props.formData.bagProcess) {
    // 检查是否存在对应的工艺选项
    const existingOptions = thirdLevelOptions.value;
    if (existingOptions.includes(props.formData.bagProcess)) {
      selectedThirdLevel.value = props.formData.bagProcess;
    } else {
      // 如果不存在，设置为"其他"
      selectedThirdLevel.value = "其他";
    }

    if (
      selectedFirstLevel.value &&
      selectedSecondLevel.value &&
      selectedSecondLevel.value !== "其他" &&
      priceData.value[selectedFirstLevel.value] &&
      priceData.value[selectedFirstLevel.value][selectedSecondLevel.value] &&
      priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][
        props.formData.bagProcess
      ]
    ) {
      const originalKeys = Object.keys(
        priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][
          props.formData.bagProcess
        ]
      );

      // 生成选项，去掉"个"字，只保留数值
      const options = originalKeys.map((key) => {
        let numericValue = key.replace(/个$/, "");
        numericValue = numericValue.replace(/米$/, "");
        return {
          label: key,
          value: numericValue,
        };
      });
      options.sort((a, b) => a.value - b.value);
      fourthLevelOptions.value = options;
    }
  }

  // 恢复数量档次选择
  const quantities = [];
  if (props.formData.quantity1 > 0) quantities.push(props.formData.quantity1.toString());
  if (props.formData.quantity2 > 0) quantities.push(props.formData.quantity2.toString());
  if (props.formData.quantity3 > 0) quantities.push(props.formData.quantity3.toString());
  selectedFourthLevel.value = quantities;
};

// 组件挂载时获取价格数据
onMounted(async () => {
  await fetchPriceData();
  // 价格数据加载完成后初始化选择状态
  if (Object.keys(priceData.value).length > 0) {
    initializeSelections();
  }
});

// 监听 formData 变化，用于处理编辑模式下的数据回显
watch(
  () => props.formData,
  (newFormData) => {
    // 只有在价格数据已加载且 formData 有有效数据时才初始化
    if (Object.keys(priceData.value).length > 0 && newFormData && newFormData.bagType) {
      initializeSelections();
    }
  },
  { deep: true, immediate: true }
);

// 监听长宽高输入变化
watch(
  () => [props.formData.l, props.formData.w, props.formData.h],
  ([l, w, h]) => {
    if (selectedSecondLevel.value === "其他" && (l || w || h)) {
      // 当选择"其他"且输入了长宽高时，触发更新
      emit("update:formData", { ...props.formData });
    }
  },
  { deep: true }
);

// 监听工艺输入变化
watch(
  () => props.formData.bagProcess,
  (newProcess) => {
    if (selectedThirdLevel.value === "其他" && newProcess) {
      // 当选择"其他"且输入了工艺名称时，触发更新
      emit("update:formData", { ...props.formData });
    }
  },
  { deep: true }
);

// 增强的 formData，包含选择的价格信息
const enhancedFormData = computed(() => {
  return {
    ...props.formData,
    selectedFirstLevel: selectedFirstLevel.value,
    selectedSecondLevel: selectedSecondLevel.value,
    selectedThirdLevel: selectedThirdLevel.value,
    selectedFourthLevel: selectedFourthLevel.value,
  };
});

// 单价计算
const unitPrice1 = computed(() => {
  if (!props.formData.price1 || !props.formData.quantity1 || props.formData.quantity1 <= 0) {
    return 0;
  }
  return props.formData.price1 / props.formData.quantity1;
});

const unitPrice2 = computed(() => {
  if (!props.formData.price2 || !props.formData.quantity2 || props.formData.quantity2 <= 0) {
    return 0;
  }
  return props.formData.price2 / props.formData.quantity2;
});

const unitPrice3 = computed(() => {
  if (!props.formData.price3 || !props.formData.quantity3 || props.formData.quantity3 <= 0) {
    return 0;
  }
  return props.formData.price3 / props.formData.quantity3;
});

// 获取指定数量档次的价格信息
const getPriceInfoByQuantity = (quantity) => {
  if (!quantity || quantity <= 0) {
    return { 零售价: 0, 会员价: 0 };
  }

  const quantityKey = `${quantity}${quantityUnit.value}`;

  if (
    selectedFirstLevel.value &&
    selectedSecondLevel.value &&
    selectedThirdLevel.value &&
    priceData.value[selectedFirstLevel.value] &&
    priceData.value[selectedFirstLevel.value][selectedSecondLevel.value] &&
    priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][
      selectedThirdLevel.value
    ] &&
    priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][selectedThirdLevel.value][
      quantityKey
    ]
  ) {
    return priceData.value[selectedFirstLevel.value][selectedSecondLevel.value][
      selectedThirdLevel.value
    ][quantityKey];
  }

  return { 零售价: 0, 会员价: 0 };
};

// 计算单价 - 会员单价和零售单价
const memberUnitPrice1 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity1);
  return priceInfo.会员价 / (props.formData.quantity1 || 1);
});

const retailUnitPrice1 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity1);
  return priceInfo.零售价 / (props.formData.quantity1 || 1);
});

const memberUnitPrice2 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity2);
  return priceInfo.会员价 / (props.formData.quantity2 || 1);
});

const retailUnitPrice2 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity2);
  return priceInfo.零售价 / (props.formData.quantity2 || 1);
});

const memberUnitPrice3 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity3);
  return priceInfo.会员价 / (props.formData.quantity3 || 1);
});

const retailUnitPrice3 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity3);
  return priceInfo.零售价 / (props.formData.quantity3 || 1);
});

// 计算总价
const memberTotalPrice1 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity1);
  return priceInfo.会员价;
});

const retailTotalPrice1 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity1);
  return priceInfo.零售价;
});

const memberTotalPrice2 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity2);
  return priceInfo.会员价;
});

const retailTotalPrice2 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity2);
  return priceInfo.零售价;
});

const memberTotalPrice3 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity3);
  return priceInfo.会员价;
});

const retailTotalPrice3 = computed(() => {
  const priceInfo = getPriceInfoByQuantity(props.formData.quantity3);
  return priceInfo.零售价;
});
</script>

<style scoped>
.unit-price-display {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}
</style>
